/**
 * 统一权限校验拦截器
 * @param children
 * @constructor
 */

import { usePathname } from "next/navigation";
import { useSelector } from "react-redux";
import { RootState } from "@/stores";
import { findAllMenuByPath } from "../../config/menu";
import checkAccess from "@/access/checkAccess";
import ACCESS_ENUM from "@/access/accessEnum";
import Forbidden from "@/app/forbidden";

const AccessLayout: React.FC<
  Readonly<{
    children: React.ReactNode;
  }>
> = ({ children }) => {
  //  获取当前登录用户
  const loginUser = useSelector((state: RootState) => state.loginUser);

  //  获取当前路径
  const pathName = usePathname();
  console.log("当前登录用户权限" + loginUser.userRole);

  //  获取当前路径所需要的权限
  const menu = findAllMenuByPath(pathName);
  const needAccess = menu?.access ?? ACCESS_ENUM.NOT_LOGIN;
  console.log("当前页面需要权限" +needAccess);

  //  权限校验
  const canAccess = checkAccess(loginUser, needAccess);
  console.log(canAccess);

  if (!canAccess) {
    return <Forbidden />;
  }
  return children;
};

export default AccessLayout;
